<template>
	<a-row>
		<a-col :span="5">
			<a-card class="cardImp" :bordered="false" :loading="cardLoading">
				<a-tree v-if="treeData.length > 0" v-model:expandedKeys="defaultExpandedKeys" :tree-data="treeData" :field-names="treeFieldNames" @select="treeSelect"></a-tree>
				<a-empty v-else :image="Empty.PRESENTED_IMAGE_SIMPLE" />
			</a-card>
		</a-col>
		<a-col :span="19">
			<a-card :bordered="false">
				<SearchForm :form-state="searchFormState" :form-fields="[{ label: '名称关键词', name: 'searchKey', span: 8 }]" @search="table.refresh(true)" @reset="handleReset" ref="searchFormRef">
					<template #searchKey="{ formState }">
						<a-input v-model:value="formState.searchKey" placeholder="请输入角色名称关键词" />
					</template>
				</SearchForm>
				<s-table
					ref="table"
					:columns="columns"
					:data="loadData"
					:expand-row-by-click="true"
					:alert="options.alert.show"
					bordered
					:row-key="(record) => record.id"
					:row-selection="options.rowSelection"
					:operator-config="operatorConfig"
				>
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'category'">
							{{ $TOOL.dictTypeData('ROLE_CATEGORY', record.category) }}
						</template>
						<template v-if="column.dataIndex === 'action'">
							<a @click="form.onOpen(record)">编辑</a>
							<a-divider type="vertical" />
							<a-popconfirm title="确定删除此角色？" @confirm="removeOrg(record)">
								<a-button type="link" danger size="small">删除 </a-button>
							</a-popconfirm>
							<a-divider type="vertical" />
							<a-dropdown>
								<a class="ant-dropdown-link">
									授权
									<DownOutlined />
								</a>
								<template #overlay>
									<a-menu>
										<a-menu-item>
											<a @click="grantResource.onOpen(record)">授权资源</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="grantPermission.onOpen(record)">授权权限</a>
										</a-menu-item>
										<a-menu-item>
											<a @click="openRoleUserSelector(record)">授权用户</a>
										</a-menu-item>
									</a-menu>
								</template>
							</a-dropdown>
						</template>
					</template>
				</s-table>
			</a-card>
		</a-col>
	</a-row>
	<grantResourceForm ref="grantResource" @successful="table.refresh(true)" />
	<grantPermissionForm ref="grantPermission" @successful="table.refresh(true)" />
	<Form ref="form" @successful="table.refresh(true)" />
	<DrawerPicker ref="drawerPicker" :showSelectedUser="true" @ok="drawerOk" @cancel="drawerCancel" :show-check-box="true" :multiple="true" v-model:visible="visibleDrawer" :type="type" />
</template>
<script setup name="sysRoleIndex">
	import { Empty, message } from 'ant-design-vue'
	import roleApi from '@/api/sys/roleApi'
	import orgApi from '@/api/sys/orgApi'
	import Form from './form.vue'
	import userSelectorPlusApi from '@/api/components/Selector/userSelectorPlusApi'
	import GrantPermissionForm from '@/pagesDefault/sys/role/grantPermissionForm.vue'
	import GrantResourceForm from '@/pagesDefault/sys/role/grantResourceForm.vue'
	const panesValues = ['人员', '部门', '岗位']
	let type = ref(panesValues[0])
	let drawerPicker = ref()
	const key = 'updatable'
	const columns = [
		{
			title: '角色名称',
			dataIndex: 'name',

			width: 150
		},
		{
			title: '角色编码',
			dataIndex: 'code',

			width: 150
		},
		{
			title: '分类',

			dataIndex: 'category'
		},
		{
			title: '排序',

			dataIndex: 'sortCode'
		},
		{
			title: '操作',

			dataIndex: 'action',
			align: 'center',
			width: 200
		}
	]
	let visibleDrawer = ref(false)
	// 人员选择器回调
	/*const userCallBack = (value) => {
		const param = {
			id: recordCacheData.value.id,
			grantInfoList: value.map((item) => {
				return item.id
			})
		}
		roleApi.roleGrantUser(param).then(() => {})
	}*/
	let drawerOk = (val) => {
		message.loading({ content: 'Loading...', key })
		const param = {
			id: recordCacheData.value.id,
			grantInfoList: val.data.members.map((item) => {
				return item.id
			})
		}
		roleApi.roleGrantUser(param).then(() => {
			message.destroy(key)
		})
	}
	let drawerCancel = () => {}
	let selectedRowKeys = ref([])
	// 列表选择配置
	const options = {
		alert: {
			show: false,
			clear: () => {
				selectedRowKeys = ref([])
			}
		},
		rowSelection: {
			onChange: (selectedRowKey, selectedRows) => {
				selectedRowKeys.value = selectedRowKey
			}
		}
	}
	// 定义tableDOM
	const table = ref()
	const form = ref()
	const grantResource = ref()
	const grantPermission = ref()
	const userselectorPlusRef = ref()
	const searchFormRef = ref()
	let searchFormState = reactive({})
	// handleReset方法
	const handleReset = () => {
		searchFormRef.value?.resetFields()
	}
	// operatorConfig配置
	const operatorConfig = computed(() => [
		{
			text: '新增角色',
			icon: 'fa fa-plus',
			onClick: () => form.value.onOpen()
		},
		{
			text: '删除',
			icon: 'fa fa-trash',
			danger: true,
			onClick: deleteBatchRole,
			disabled: selectedRowKeys.value.length === 0
		}
	])
	// 默认展开的节点
	let defaultExpandedKeys = ref([])
	const treeData = ref([])
	// 替换treeNode 中 title,key,children
	const treeFieldNames = { children: 'children', title: 'name', key: 'id' }
	const cardLoading = ref(true)
	// 记录数据
	const recordCacheData = ref({})
	// 表格查询 返回 Promise 对象
	const loadData = (parameter) => {
		let param = Object.assign(parameter, searchFormState)
		return roleApi.rolePage(param).then((res) => {
			return res
		})
	}
	// 加载左侧的树
	orgApi.orgTree().then((res) => {
		cardLoading.value = false
		if (res !== null) {
			// 树中插入全局角色类型
			const globalRoleType = [
				{
					id: 'GLOBAL',
					parentId: '-1',
					name: '全局'
				}
			]
			treeData.value = globalRoleType.concat(res)
			// 默认展开2级
			treeData.value.forEach((item) => {
				// 因为0的顶级
				if (item.parentId === '0') {
					defaultExpandedKeys.value.push(item.id)
					// 取到下级ID
					if (item.children) {
						item.children.forEach((items) => {
							defaultExpandedKeys.value.push(items.id)
						})
					}
				}
			})
		}
	})
	// 点击树查询
	const treeSelect = (selectedKeys) => {
		if (selectedKeys.length > 0) {
			if (selectedKeys[0] === 'GLOBAL') {
				searchFormState.category = selectedKeys[0]
				delete searchFormState.orgId
			} else {
				searchFormState.orgId = selectedKeys.toString()
				delete searchFormState.category
			}
		} else {
			delete searchFormState.category
			delete searchFormState.orgId
		}
		table.value.refresh(true)
	}

	// 删除
	const removeOrg = (record) => {
		let params = [
			{
				id: record.id
			}
		]
		roleApi.roleDelete(params).then(() => {
			table.value.refresh(true)
		})
	}
	// 批量删除
	const deleteBatchRole = () => {
		if (selectedRowKeys.value.length < 1) {
			message.warning('请选择一条或多条数据')
			return false
		}
		const params = selectedRowKeys.value.map((m) => {
			return {
				id: m
			}
		})
		roleApi.roleDelete(params).then(() => {
			table.value.clearRefreshSelected()
		})
	}
	// 打开用户选择器
	const openRoleUserSelector = (record) => {
		recordCacheData.value = record
		visibleDrawer.value = true
		const param = {
			id: record.id
		}
		drawerPicker.value.setMembersSelectedLoading(true)
		roleApi.roleOwnUser(param).then((data) => {
			if (!!data && data.length > 0) {
				const res = userSelectorPlusApi
					.getUsersByUserIds(
						'/sys/user/ids',
						data.map((res) => {
							return {
								id: res
							}
						})
					)
					.then((res) => {
						drawerPicker.value.setMembers(res)
						drawerPicker.value.setMembersSelectedLoading(false)
					})
			} else {
				drawerPicker.value.setMembers([])
				drawerPicker.value.setMembersSelectedLoading(false)
			}
		})
	}
</script>
<style scoped>
	.cardImp {
		margin-right: 10px;
	}
	.ant-form-item {
		margin-bottom: 0 !important;
	}
	.primaryAdd {
		margin-right: 10px;
	}
	.snowy-buttom-left {
		margin-left: 8px;
	}
</style>
